use std::sync::Arc;

use axum::Router;
use dotenv::dotenv;
use notepad::{api_web, config, AppState};
use sqlx::postgres::PgPoolOptions;
use tokio::net::TcpListener;
use tower_http::cors::{Any, CorsLayer};

#[tokio::main]
async fn main() {
    dotenv().ok();
    tracing_subscriber::fmt::init();
    let cfg = config::Config::from_env().unwrap();
    let pool = PgPoolOptions::new()
        .max_connections(cfg.db.max_conns)
        .connect(&cfg.db.dsn)
        .await
        .unwrap();
    let app_addr = cfg.app.addr.clone();
    let state = Arc::new(AppState {
        cfg: Arc::new(cfg),
        pool: Arc::new(pool),
    });

    let tcp_listener = TcpListener::bind(&app_addr).await.unwrap();

    tracing::info!("服务监听于：{}", &app_addr);

    let app = Router::new()
        .nest("/", api_web::init_router(state.clone()))
        .layer(
            CorsLayer::new()
                .allow_headers(Any)
                .allow_methods(Any)
                .allow_origin(Any),
        );
    axum::serve(tcp_listener, app).await.unwrap();
    // let pool = PgPoolOptions::new()
    //     .connect("postgresql://notepad:notepad@127.0.0.1:5432/notepad")
    //     .await
    //     .unwrap();

    /*
    let id = xid::new().to_string();
    let m = model::Note {
        id,
        content: "Hello, 世界".to_string(),
        is_md: false,
        has_view_pwd: false,
        view_pwd: "".to_string(),
        has_man_pwd: false,
        man_pwd: "".to_string(),
        is_arch: false,
        dateline: chrono::Local::now(),
    };
    let id = m.insert(&pool).await.unwrap();
    println!("{}", id);
    */

    /*
    let id = "cq15f4cdrfapi9e42dfg".to_string();
    let m = model::Note {
        id,
        content: "**Hello, 世界**".to_string(),
        is_md: true,
        has_view_pwd: false,
        view_pwd: "".to_string(),
        has_man_pwd: false,
        man_pwd: "".to_string(),
        is_arch: false,
        dateline: chrono::Local::now(),
    };
    let aff = m.update(&pool).await.unwrap();
    println!("{}", aff);
     */

    /*
    let id = "cq15f4cdrfapi9e42dfg".to_string();

    let f = model::NoteFindFilter {
        by: model::NoteFindBy::Id(id.clone()),
    };

    let fm = model::Note::find(&pool, &f).await.unwrap();
    println!("{:?}", fm);
     */

    /*
    let pq = model::NotePaginateReq::new(0);
    let f = model::NoteListFilter { pq, content: None };
    let p = model::Note::list(&pool, &f).await.unwrap();
    println!("{:?}", p);
    */

    /*
    let id = "cq15f4cdrfapi9e42dfg".to_string();
    let aff = model::Note::del(&pool, &id).await.unwrap();
    println!("{}", aff);
    */

    /*
    let id = "cq15f4cdrfapi9e42dfg".to_string();
    let aff = model::Note::update_is_md(&pool, &true, &id).await.unwrap();
    println!("{}", aff);
    */
}
